package com.miku.project.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miku.mikuapicommon.model.entity.InterfaceInfo;
import com.miku.project.common.ErrorCode;
import com.miku.project.exception.BusinessException;
import com.miku.project.mapper.InterfaceInfoMapper;
import com.miku.project.service.InterfaceInfoService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 接口信息服务实现类
 *
 * @author <a href="https://gitee.com/deng-taotao-eee">miku</a>
 * @from <a href=""></a>
 */
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService {

    @Override
    public void validInterfaceInfo(InterfaceInfo interfaceInfo, boolean add) {
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String name = interfaceInfo.getName();
        String url = interfaceInfo.getUrl();
        String method = interfaceInfo.getMethod();

        String description = interfaceInfo.getDescription();
        Integer reduceScore = Math.toIntExact(interfaceInfo.getReduceScore());
        // 创建时，所有参数必须非空
        if (add) {
           if (StringUtils.isAnyBlank(name,url,method)){
               throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
           }
        }
        // 更新时，method不能为空，其他参数可以选择性更新
        if (StringUtils.isNotBlank(method)){
            interfaceInfo.setMethod(method.trim().toUpperCase());
        }
        //url不为空
        if (StringUtils.isNotBlank(url)){
            interfaceInfo.setUrl(url.trim());
        }

        if(ObjectUtils.isNotEmpty(reduceScore) && reduceScore<0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"积分不能为负数");
        }
        if (StringUtils.isNotBlank(name) && name.length() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "名称过长");
        }
        if (StringUtils.isNotBlank(description) && description.length() > 200) {

            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口描述过长");
        }
    }

    /**
     * 更新总调用次数
     *
     * @param interfaceId
     * @return
     */
    @Override
    public boolean updateTotalInvokes(long interfaceId) {
        LambdaUpdateWrapper<InterfaceInfo> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.eq(InterfaceInfo::getId,interfaceId);
        updateWrapper.setSql("totalInvokes = totalInvokes + 1");
        return this.update(updateWrapper);
    }

}




